package com.zk.babala.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.zk.babala.BabalaApp;
import com.zk.babala.R;
import com.zk.babala.entity.Movie;
import com.zk.babala.entity.PlayNumInfo;
import com.zk.babala.module.EpisodeControlBar;
import com.zk.babala.util.HistoryUtil;

import java.util.List;

/**
 * @Author: zhangke
 * @Date: 2025/1/13 9:36
 */
public class WebViewActivity extends AppCompatActivity {
    private long outKeyTime = 0;
    //视频信息
    private Movie movie;
    //播放集数
    private PlayNumInfo playNum;
    private String playUrl;
    private List<PlayNumInfo> currLinePlayNumList;
    private WebView webView;
    private EpisodeControlBar episodeControlBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview_activity);
        webView = findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setMediaPlaybackRequiresUserGesture(false);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
                int keyCode = event.getKeyCode();
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    //后退30s
                    if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                        String js = "javascript:art.controls.show=true;art.backward=30";
                        webView.loadUrl(js);
                    }
                    //快进30s
                    if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {

                        String js = "javascript:art.controls.show=true;art.forward=30";
                        webView.loadUrl(js);
                    }
                    //播放or暂停
                    if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
                        if (event.getAction() == KeyEvent.ACTION_DOWN) {
                            String js = "javascript:art.toggle()";
                            webView.loadUrl(js);
                        }
                    }
                }
                return true;
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onPageFinished(view, url);
                String js = "javascript:art.fullscreenWeb=true";
                view.loadUrl(js);
            }

        });
        //js弹窗
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder b = new AlertDialog.Builder(view.getContext());
                b.setTitle("Alert");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                b.setCancelable(false);
                b.create().show();
                return true;
            }

        });
        Intent intent = getIntent();
        movie = (Movie) intent.getSerializableExtra("movie");
        playNum = (PlayNumInfo) intent.getSerializableExtra("playNum");
        currLinePlayNumList = (List<PlayNumInfo>) intent.getSerializableExtra("currLinePlayNumList");
        // 初始化 EpisodeControlBar
        episodeControlBar = findViewById(R.id.episode_control_bar);
        episodeControlBar.setAllEpisodes(currLinePlayNumList);
        // 设置选集选择监听器
        episodeControlBar.setOnEpisodeSelectedListener(playNumInfo -> {
            playNum = playNumInfo;
            play();
        });
        play();
    }

    public void play() {
        playUrl = BabalaApp.getSourceParse().getPlayUrl(playNum.getPageUrl());
        movie.setPlayHis(playNum.getTitle());
        movie.setId(playNum.getId());
        if (currLinePlayNumList.size() > 5) {
            HistoryUtil.getHistoryInstance().addMovieHis(movie);
        }
        //访问网页
        webView.loadUrl(playUrl);
        Toast.makeText(getBaseContext(), "正在播放: " + playNum.getTitle(), Toast.LENGTH_LONG).show();
        episodeControlBar.hide();
        episodeControlBar.setEpisodes(playNum);
    }

    public void playNext() {
        if ((currLinePlayNumList.size() - 1) == playNum.getId()) {
            Toast.makeText(getBaseContext(), "播放完毕！", Toast.LENGTH_LONG).show();
            finish();
        } else {
            playNum = currLinePlayNumList.get(playNum.getId() + 1);
            play();
        }
    }

    public void playPre() {
        if (0 == playNum.getId()) {
            Toast.makeText(getBaseContext(), "正在播放: " + playNum.getTitle(), Toast.LENGTH_LONG).show();
        } else {
            playNum = currLinePlayNumList.get(playNum.getId() - 1);
            play();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (episodeControlBar.isShown()) {
                episodeControlBar.hide();
                return true;
            }
            //退出
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if ((System.currentTimeMillis() - outKeyTime) > 1000) {
                    Toast.makeText(this, "再按一次退出播放！", Toast.LENGTH_SHORT).show();
                    outKeyTime = System.currentTimeMillis();
                    return true;
                }
            }

            if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                episodeControlBar.show();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


}
